<template>
  <el-tabs v-model="currentTab" type="border-card" class="j-tabs" @tab-change="onTabChange">
    <el-tab-pane name="1" label="Residential Proxies">
      <div class="proxy-form mt-0">
        <div class="form-main">
          <div class="title"><span>Build Agent </span>（Support HTTP/HTTPS SOCKS5）</div>
          <div class="form">
            <el-form label-width="120px" :model="proxyForm" ref="proxyFormRef" :rules="rules" size="large">
              <el-form-item label="Country/Place" prop="country">
                <el-select
                  v-model="proxyForm.country"
                  filterable
                  clearable
                  placeholder="Please select a country/place"
                  class="full-width"
                  @change="onCountryChange"
                >
                  <el-option v-for="item in countryList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="Area" prop="region">
                <el-select
                  v-model="proxyForm.region"
                  filterable
                  clearable
                  placeholder="Please select a area"
                  class="full-width"
                  @change="onRegionChange"
                >
                  <el-option v-for="item in regionList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="City" prop="city">
                <el-select
                  v-model="proxyForm.city"
                  filterable
                  clearable
                  placeholder="Please select a city"
                  class="full-width"
                  @change="onCityChange"
                >
                  <el-option v-for="item in cityList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="Access point" prop="node">
                <el-select v-model="proxyForm.node" placeholder="Please select an access point" class="full-width">
                  <template v-for="(item, index) in pointsList" :key="item.label + '-' + index">
                    <el-option v-if="item.label == proxyForm.country" :label="item.value" :value="item.value" />
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item label="IP Time" prop="time">
                <el-select v-model="proxyForm.time" placeholder="Please select an valid duration(minutes)" class="full-width">
                  <el-option label="5" :value="5" />
                  <el-option label="10" :value="10" />
                  <el-option label="15" :value="15" />
                  <el-option label="30" :value="30" />
                  <el-option label="45" :value="45" />
                  <el-option label="60" :value="60" />
                  <el-option label="90" :value="90" />
                </el-select>
              </el-form-item>
              <el-form-item label="Number" prop="quantity">
                <el-input
                  v-model.number="proxyForm.quantity"
                  type="number"
                  autocomplete="off"
                  placeholder="Please enter the account number"
                />
              </el-form-item>
              <el-form-item label="Password" prop="password">
                <div class="pwd-item">
                  <el-input v-model="proxyForm.password" placeholder="Password required for first-time generation" />
                  <!-- <el-button type="primary">Change Password</el-button> -->
                </div>
              </el-form-item>
              <el-form-item>
                <div style="white-space: nowrap">
                  <el-button
                    style="width: 134px"
                    class="primary-btn"
                    type="primary"
                    :disabled="loading"
                    :loading="loading"
                    @click="onSubmit(proxyFormRef)"
                    >Submit</el-button
                  >
                  <el-button style="width: 134px" class="info-btn" type="primary" :disabled="loading" @click="onReset(proxyFormRef)">Reset</el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="form-tips">
          <el-scrollbar height="540px">
            <p class="title">Use Description</p>
            <p class="info">All users can automatically generate accounts, and can also specify countries, states, and cities Set the IP usage duration (IP usage duration refers to the time from the beginning of network connection to the end, and only changes the IP address and does not interrupt the network). </p>
            <p class="info">The proxy password is set by the user, which can improve security.</p>
            <p class="info">We have purchased AWS CDN service, and all networks are connected nearby. Currently, we provide three proxy server access points:</p>
            <p class="info">gate1.ipxproxy.com(Please choose to use IP from South and North American countries)</p>
            <p class="info">gate2.ipxproxy.com (Please select if using Asia Pacific country IP)</p>
            <p class="info">gate3.ipxproxy.com(please choose to use IP from European and African countries)</p>
            <p class="info">All proxy service ports: 7778</p>
            <p class="title mt-10">Example Description</p>
            <p class="info">For example, proxy sub accounts：IPX_1000_US_001_0002_5_9978</p>
            <p class="info"><b>IPX_1000：</b>User ID (fixed and unchanged)</p>
            <p class="info"><b>US：</b>Country Code (US, United States)</p>
            <p class="info"><b>001：</b>The code of a state in a US country (specifically, which state in the United States is represented by the country, region, state, and city code table)</p>
            <p class="info"><b>0002：</b>The code of a city under the state 001 (please refer to the city code table for specific countries, regions, and states)</p>
            <p class="info"><b>5：</b>IP usage duration (in minutes, minimum duration 5 minutes, maximum 90 minutes, must be greater than or equal to 5)</p>
            <p class="info"><b>1001：</b>sessionID, consisting of English and numbers, with a length of 1-32 digits. Different session IDs represent different proxy sub accounts. By modifying the session ID, many proxy sub accounts can be generated</p>
            <p class="info">For example：IPX_1000_US_001_0002_5_1001，IPX_1001_US_001_0002_5_1002，which is two proxy sub accounts </p>
            <p class="title mt-10">Advanced description</p>
            <p class="info">1、If only the state needs to be located, then the proxy sub account is composed of:</p>
            <p class="info"><b>IPX1000</b>_US_001__5_1001(representing obtaining a 5-minute IP address from State 001 in the United States)</p>
            <p class="info"><b>IPX1000</b>_US_001__10_1001(representing obtaining a 10 minute IP address from State 001 in the United States)</p>
            <p class="info">Note: There are two '_' between the state code and the duration code</p>
            <p class="info">2、If only the country needs to be located, then the proxy sub account is composed of:</p>
            <p class="info"><b>IPX1000</b>_US___5_1001 (representing obtaining an IP in the United States with a usage time of 5 minutes)</p>
            <p class="info"><b>IPX1000</b>_US___10_1001 (representing obtaining an IP in the United States with a usage time of 10 minutes)</p>
            <p class="info"><b>Note: </b>There are three '_' between the country code and the duration code</p>
            <p class="info mt-10">The same proxy sub account is assigned the same proxy IP at the same time, and the same proxy sub account can be used on different devices simultaneously, but the IP is the same</p>
          </el-scrollbar>
        </div>
      </div>
      <div class="mt-20">
        <el-table :data="data" border stripe style="width: 100%" class="j-table mt-0">
          <el-table-column prop="created_time" label="Create time" />
          <el-table-column prop="country" label="Country/Region" />
          <el-table-column prop="region" label="Region/City" />
          <el-table-column prop="quantity" label="Quantity" />
          <el-table-column prop="action" label="Operation" width="254px">
            <template #default="scope">
              <el-button @click="onDownload(scope.row)" type="primary" text :icon="Download">Download</el-button>
              <el-button @click="onDelete(scope.row)" type="primary" text :icon="Delete" style="margin-left: 0">Delete</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="j-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="page"
            :pageSize="limit"
            :total="total"
            @current-change="onCurrentChange"
          />
        </div>
      </div>
    </el-tab-pane>
    <el-tab-pane name="2" label="Usage Record">
      <Record ref="recordRef" @page-loading="onPgeLoading" />
    </el-tab-pane>
  </el-tabs>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { regionApi, proxyCreateApi, proxyDownloadApi, proxyDeleteApi } from '@/api/index';
  import type { FormInstance, FormRules } from 'element-plus';
  import { Download, Delete } from '@element-plus/icons-vue';
  import Record from './components/record.vue';

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const props = defineProps<{
    data: Array;
    limit: any;
    page: any;
    total: any;
  }>();

  const emits = defineEmits<{
    (event: 'confirm'): void;
    (event: 'page-change'): void;
    (event: 'page-loading'): void;
  }>();

  const recordRef = ref();
  const loading = ref(false);
  const currentTab = ref('1');
  const proxyFormRef = ref<FormInstance>();
  const proxyForm = reactive({
    country: '',
    region: '',
    city: '',
    node: '',
    time: '',
    quantity: '',
    password: '',
  });
  const rules = reactive<FormRules>({
    country: [{ required: true, message: 'Please select a country/place', trigger: 'change' }],
    region: [{ required: true, message: 'Please select a area', trigger: 'change' }],
    city: [{ required: true, message: 'Please select a city', trigger: 'change' }],
    node: [{ required: true, message: 'Please select an access point', trigger: 'change' }],
    time: [{ required: true, message: 'Please select an valid duration(minutes)', trigger: 'change' }],
    quantity: [{ required: true, type: 'number', message: 'Please enter the account number', trigger: 'blur' }],
    password: [{ required: true, message: 'Password required for first-time generation', trigger: 'blur' }],
  });

  const countryList = ref([]);
  const regionList = ref([]);
  const cityList = ref([]);
  const pointsList = ref([]);

  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        onProxyCreate();
      }
    });
  };

  const onReset = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
  };

  const onProxyCreate = async () => {
    if (loading.value) return false;
    loading.value = true;
    proxyCreateApi(proxyForm)
      .then((res) => {
        loading.value = false;
        if (res.errcode == 0) {
          ElMessage.success(res.message || res.errmsg);
          onCurrentChange(1);
          proxyFormRef.value.resetFields();
          nextTick(() => {
            proxyFormRef.value.clearValidate();
          });
        } else {
          ElMessage.error(res.message || res.errmsg);
        }
      })
      .catch((err) => {
        console.log('err', err);
        loading.value = false;
        ElMessage.error(res.message || res.errmsg);
      });
  };

  const onDownload = (row) => {
    // if (loading.value) return false;
    loading.value = true;
    proxyDownloadApi({ batch_id: row.id })
      .then((res) => {
        loading.value = false;
        if (res.message || res.errmsg) {
          ElMessage.success(res.message || res.errmsg);
          return false;
        }
        let url = window.URL.createObjectURL(new Blob([res]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', `${new Date().getTime()}_proxy.text`);
        document.body.appendChild(link);
        link.click();
      })
      .catch((err) => {
        console.log('err', err);
        loading.value = false;
        ElMessage.error(err.message);
      });
  };

  const onDelete = (row) => {
    ElMessageBox.confirm('Delete or not?', 'Alert', {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning',
    })
      .then(() => {
        onDeleteFn(row);
      })
      .catch(() => {});
  };

  const onDeleteFn = async (row) => {
    // if (loading.value) return false;
    loading.value = true;
    proxyDeleteApi({ batch_id: row.id })
      .then((res) => {
        loading.value = false;
        if (res.errcode == 0) {
          ElMessage.success(res.message || res.errmsg);
          onCurrentChange(props.page);
        } else {
          ElMessage.error(res.message || res.errmsg);
        }
      })
      .catch((err) => {
        console.log('err', err);
        loading.value = false;
        ElMessage.error(err.message);
      });
  };

  const onTabChange = (val) => {
    if (val == '1') {
      emits('page-change', 1);
    } else if (val == '2') {
      recordRef.value.onPageChange('traffic', 1);
    }
  };

  const onCurrentChange = (val) => {
    emits('page-change', val);
  };

  const onCountryChange = (val) => {
    if (val) {
      getRegion('region', val);
    }
  };

  const onRegionChange = (val) => {
    if (val) {
      getRegion('city', val);
    }
  };

  const onCityChange = () => {};

  const getRegion = async (type, code = '') => {
    regionApi({
      type: type,
      code: code,
    })
      .then((res) => {
        if (res.data) {
          if (type == 'country') {
            countryList.value = res.data;
          }
          if (type == 'region') {
            regionList.value = res.data;
          }
          if (type == 'city') {
            cityList.value = res.data;
          }
          if (res.points) {
            pointsList.value = [];
            for (let i in res.points) {
              pointsList.value.push({
                label: i,
                value: res.points[i],
              });
            }
          }
        }
      })
      .catch((err) => {
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const onPgeLoading = (val) => {
    emits('page-loading', val);
  };

  onMounted(() => {
    getRegion('country');
  });
</script>

<style scoped lang="scss"></style>
